package com.csx.micrometer.simple.threadpool.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author cuisongxu
 * @date 2023/2/7 14:40
 */
@RequestMapping("/threadpool")
@RestController
public class ThreadpoolMicrometerController {

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @PostMapping("/execute/{taskNum}")
    public String executeTask(@PathVariable("taskNum") int taskNum) {

        List<Runnable> runnableList = new ArrayList<>();
        for (int i = 0; i < taskNum; i++) {
            Runnable runnable = () -> {
                try {
                    Thread.sleep(nextInt(100, 2000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
            runnableList.add(runnable);
        }
        for (Runnable runnable : runnableList) {
            threadPoolExecutor.execute(runnable);
        }
        return "异步线程正在执行任务中";
    }

    private int nextInt(int start, int end) {
        if(end - start < 0) {
            throw new RuntimeException();
        }
        Random random = new Random();
        return start + random.nextInt(end - start);
    }

}
